#include "stm32f10x.h"

//从机选择
void MySPI_W_CS(uint8_t Bitvalue)
 {
    GPIO_WriteBit(GPIOA, GPIO_Pin_4,(BitAction)Bitvalue);
 }


// SPI 写数据

// SPI初始化
void MySPI_Init(void)
{   //时钟使能
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
     RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1,ENABLE);
    //初始化GPIO
    GPIO_InitTypeDef gpio_def ;
    //pp   cs 从机选择 推挽输出模式
    gpio_def.GPIO_Mode  = GPIO_Mode_Out_PP; 
    gpio_def.GPIO_Pin = GPIO_Pin_4;
    gpio_def.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &gpio_def);

   //SCK和MOSI要进行复用推挽输出
   gpio_def.GPIO_Mode  = GPIO_Mode_AF_PP; 
   gpio_def.GPIO_Pin = GPIO_Pin_5 |GPIO_Pin_7;
   gpio_def.GPIO_Speed = GPIO_Speed_50MHz;
   GPIO_Init(GPIOA, &gpio_def);

      //MISO要进行上拉输入配置
   gpio_def.GPIO_Mode  = GPIO_Mode_IPU; 
   gpio_def.GPIO_Pin = GPIO_Pin_6;
   gpio_def.GPIO_Speed = GPIO_Speed_50MHz;
   GPIO_Init(GPIOA, &gpio_def);


   //SPI外设初始化
   SPI_InitTypeDef spi_def;
   spi_def.SPI_Mode = SPI_Mode_Master;//主机模式
   spi_def.SPI_Direction = SPI_Direction_2Lines_FullDuplex;//全双工
   spi_def.SPI_DataSize = SPI_DataSize_8b;
   spi_def.SPI_FirstBit = SPI_FirstBit_MSB;//高位在前
   spi_def.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_128;//分频系数
   spi_def.SPI_CPHA = SPI_CPHA_1Edge;//第一个边沿采样
   spi_def.SPI_CPOL = SPI_CPOL_Low;//空闲时为低电平
   spi_def.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
   spi_def.SPI_NSS = SPI_NSS_Soft;//软件控制NSS
   spi_def.SPI_CRCPolynomial = 7;//CRC多项式
   SPI_Init(SPI1,&spi_def);//初始化SPI1
   SPI_Cmd(SPI1,ENABLE);//使能SPI1

   MySPI_W_CS(1);//默认为高电平 
}

//SPI启动
void MySPI_Start(void)
{
    MySPI_W_CS(0);
}

//SPI 结束
 void MySPI_Stop(void)
 {
    MySPI_W_CS(1);
}

//SPI 交换数据
uint8_t MySPI_swap(uint8_t ByteSend)
{
   //等待发送缓冲区为空
   while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_TXE)!=SET);
   SPI_I2S_SendData(SPI1,ByteSend);
   //等待接收缓冲区为空
   while(SPI_I2S_GetFlagStatus(SPI1,SPI_I2S_FLAG_RXNE)!=SET);
   return SPI_I2S_ReceiveData(SPI1);
}
